package com.hyq.learn.rabbitmq.producer;

import com.hyq.learn.common.util.SnakeJsonUtils;
import com.hyq.learn.rabbitmq.constant.RoutingKeyConstants;
import com.hyq.learn.rabbitmq.message.CommonMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author heyuqin
 * @date 2024/8/20 17:25
 */
@Component
public class RabbitProducer {
    private static final Logger LOGGER = LoggerFactory.getLogger(RabbitProducer.class);
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void doSend(String message) {
        doSend(RoutingKeyConstants.DIRECT_ROUTING_KEY, message);
    }

    public void doSend(String routingKey, String message) {
        CommonMessage commonMessage = new CommonMessage(message);
        String json = SnakeJsonUtils.toJson(commonMessage);
        // 使用默认的交换机
        LOGGER.info("send message, use default exchange, routingKey:{}, message:{}", routingKey, json);
        rabbitTemplate.convertAndSend(routingKey, json);
    }

    public void doSend(String exchange, String routingKey, String message) {
        CommonMessage commonMessage = new CommonMessage(message);
        String json = SnakeJsonUtils.toJson(commonMessage);
        LOGGER.info("send message,exchange:{}, routingKey:{}, message:{}", exchange, routingKey, json);
        rabbitTemplate.convertAndSend(exchange, routingKey, json);
    }
}
